/**
 * 邮件发送模板详情页
 */
import React from 'react';
import { Form, Card, message } from 'antd';
import { get as getPath } from 'object-path';
import FileUpload from '@/components/Custom/FileUpload';
import { useRequest, defaultFormatResult } from '@/hooks';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import BraftEditor from 'braft-editor';
import { transformFileList } from '../utils';
import { PreviewModal } from './containers';
import { getChannelColumns, getEmailTemplate } from './service';
import styles from './index.less';

const templateTypeList = [
    { label: '发布/上线模板', value: 1 },
    { label: '更新模板', value: 2 },
    { label: '下线模板', value: 3 }
];

const EmailTemplateDetail = ({ form, location }) => {
    const { query } = location;
    const { getFieldDecorator } = form;
    const modalRef = React.useRef(null);

    const { data: info, loading, run: fetchDetail } = useRequest(getEmailTemplate, {
        manual: true,
        ...defaultFormatResult
    });

    // 获取渠道列表
    const { data: channelColumns } = useRequest(getChannelColumns, {
        initialData: [],
        formatResult: result => {
            const { code, data: resData, msg } = result;
            if (code === 10000) {
                return resData?.map(item => ({
                    title: item.columnName,
                    value: item.columnCode,
                    disabled: item.columnCode === 'positionName'
                }));
            }
            message.error(msg);
            return [];
        }
    });

    React.useEffect(() => {
        if (query?.id) {
            fetchDetail(query?.id);
        }
    }, []);

    const recruitColumns = React.useMemo(() => {
        if (info?.recruitColumns) {
            return channelColumns.filter(item => info?.recruitColumns.includes(item.value)).map(item => item.title);
        }
        return [];
    }, [info, channelColumns]);

    React.useEffect(() => {
        if (getPath(info, 'recruitChannelTemplateAttachmentFile')) {
            form.setFieldsValue({
                resourceRelation: transformFileList(getPath(info, 'recruitChannelTemplateAttachmentFile', []))
            });
        }
    }, [info]);

    const handlePreview = e => {
        e.preventDefault();
        const { subject, openingRemarks } = info;
        let str = openingRemarks || '';
        str += '<br/>';
        recruitColumns.forEach(item => {
            str += `<p style="text-indent:${6 - item?.length}em;">${item}：</p>`;
        });
        modalRef.current.show({
            subject,
            openingRemarks: str,
            resourceRelation: form.getFieldValue('resourceRelation') || null
        });
    };

    return (
        <PageHeaderWrapper>
            <Card title="模板详情" bordered={false} loading={loading}>
                <Form className={styles.formWrap} style={{ marginTop: 24 }}>
                    <Form.Item label="名称" className={styles.detailItem} required>
                        {getPath(info, 'templateName', '')}
                    </Form.Item>
                    <Form.Item label="邮件主题" className={styles.detailItem} required>
                        {getPath(info, 'subject', '')}
                    </Form.Item>
                    <Form.Item label="模板类型" className={styles.detailItem} required>
                        {templateTypeList.find(item => item.value === getPath(info, 'templateType'))?.label || ''}
                    </Form.Item>
                    <Form.Item label="是否通用" className={styles.detailItem}>
                        {getPath(info, 'generalType', false) ? '是' : '否'}
                    </Form.Item>
                    <Form.Item label="模板附件" className={styles.detailItem}>
                        {getFieldDecorator('resourceRelation')(<FileUpload disabled> </FileUpload>)}
                    </Form.Item>
                    <Form.Item label="邮件内容" className={styles.detailItem} required>
                        招聘需求字段+其他内容&nbsp;&nbsp;<a onClick={handlePreview}>效果预览</a>
                    </Form.Item>
                    <Form.Item label="招聘需求字段" className={styles.detailItem} required>
                        {recruitColumns?.join('；')}
                    </Form.Item>
                    <Form.Item label="其他内容" required>
                        <BraftEditor
                            controls={[]}
                            readOnly
                            contentStyle={{ height: 600 }}
                            value={BraftEditor.createEditorState(getPath(info, 'openingRemarks', null) || null)}
                        />
                    </Form.Item>
                </Form>
                <PreviewModal ref={modalRef} />
            </Card>
        </PageHeaderWrapper>
    );
};

export default Form.create({})(EmailTemplateDetail);
